<template>
  <el-dialog :title="isEdit ? '修改门店' : '添加门店'" :visible="dialogVisible" width="40%" :before-close="handleClose">
    <el-form size="mini" :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
      <el-form-item label="门店名称" prop="name">
        <el-input class="elinput" v-model="ruleForm.name"></el-input>
      </el-form-item>
      <el-form-item label="地址" prop="address">
        <el-input class="elinput" v-model="ruleForm.address"></el-input>
      </el-form-item>
      <el-form-item label="联系电话" prop="tel">
        <el-input class="elinput" v-model="ruleForm.tel"></el-input>
      </el-form-item>
      <el-form-item label="营业时间" prop="startTime">
        <el-time-picker v-model="ruleForm.startTime" value-format="HH:mm:ss" format="HH:mm:ss" placeholder="选择时间"> </el-time-picker>
        <span style="margin: 0 10px">-</span>
        <el-time-picker v-model="ruleForm.endTime" value-format="HH:mm:ss" format="HH:mm:ss" placeholder="选择时间"> </el-time-picker>
      </el-form-item>
      <el-form-item label="服务范围" prop="services">
        <el-select v-model="ruleForm.services" placeholder="请选择">
          <el-option label="区域一" value="区域一"></el-option>
          <el-option label="区域二" value="区域二"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="门店logo" prop="logo">
        <el-upload
          class="avatar-uploader"
          :action="uploadUrl"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
          :headers="uploadHeaders"
        >
          <img v-if="imageUrl" :src="imageUrl" class="avatar" />
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>
      <el-form-item label="店主" prop="username">
        <el-input class="elinput" v-model="ruleForm.username"></el-input>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button type="primary" @click="handleSubmit('ruleForm')">确 定</el-button>
      <el-button @click="handleCancel">取 消</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { add, update } from '@/api/stores'
export default {
  name: 'DialogStores',
  props: {
    dialogVisible: {
      type: Boolean,
      default: false,
    },
    isEdit: {
      type: Boolean,
      default: false,
    },
    editData: {
      type: Object,
      default: () => {},
    },
  },
  data() {
    return {
      imageUrl: '',
      uploadUrl: process.env.VUE_APP_UPLOAD_API_URL,
      uploadHeaders: {
        Authorization: localStorage.getItem('token'),
      },
      ruleForm: {
        id: 0,
        name: '',
        address: '',
        tel: '',
        startTime: '',
        endTime: '',
        services: '',
        logo: '',
        username: '',
      },
      rules: {
        name: [{ required: true, message: '请输入门店名称', trigger: 'blur' }],
        address: [{ required: true, message: '请输入地址', trigger: 'blur' }],
        tel: [{ required: true, message: '请输入联系电话', trigger: 'blur' }],
        startTime: [{ required: true, message: '请选择开始营业时间', trigger: 'change' }],
        endTime: [{ required: true, message: '请选择结束营业时间', trigger: 'change' }],
        services: [{ required: true, message: '请选择服务范围', trigger: 'change' }],
        username: [{ required: true, message: '请输入店主姓名', trigger: 'blur' }],
      },
    }
  },
  watch: {
    // 监听编辑数据的变化
    editData: {
      handler(newVal) {
        if (newVal && Object.keys(newVal).length > 0) {
          this.ruleForm = { ...newVal }
          // 处理图片显示
          if (newVal.logo) {
            this.imageUrl = process.env.VUE_APP_UPLOAD_BASE_URL + newVal.logo
          }
        } else {
          this.resetForm()
        }
      },
      immediate: true,
    },
    dialogVisible: {
      handler(newVal) {
        if (newVal && this.isEdit && this.editData) {
          // 在对话框打开时重新设置图片显示
          this.$nextTick(() => {
            if (this.editData.logo) {
              this.imageUrl = process.env.VUE_APP_UPLOAD_BASE_URL + this.editData.logo
            }
          })
        }
      },
    },
  },
  methods: {
    // 文件
    handleAvatarSuccess(res, file) {
      // 保存图片路径到表单数据中
      this.ruleForm.logo = res.data
      this.imageUrl = URL.createObjectURL(file.raw)
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    handleClose() {
      this.$emit('handleCancel', false)
    },
    handleCancel() {
      this.$emit('handleCancel', false)
    },
    resetForm() {
      this.ruleForm = {
        id: 0,
        name: '',
        address: '',
        tel: '',
        startTime: '',
        endTime: '',
        services: '',
        logo: '',
        username: '',
      }
      this.imageUrl = ''
    },
    handleSubmit(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          try {
            if (this.isEdit) {
              // 编辑模式
              console.log('Editing store:', this.ruleForm)
              await update(this.ruleForm)
              this.$message.success('编辑成功')
            } else {
              // 添加模式
              console.log('Adding new store:', this.ruleForm)
              await add(this.ruleForm)
              this.$message.success('添加成功')
            }
            this.resetForm()
            this.$emit('refreshList')
          } catch (error) {
            console.error('操作失败:', error)
            this.$message.error(this.isEdit ? '编辑失败' : '添加失败')
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
  },
}
</script>

<style lang="less" scoped>
/* 文件上传 */
/deep/ .avatar-uploader .el-upload {
  border: 0.1px dashed #d5d5d5;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  background-color: #fafafa;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #7e7e7e;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
}

.avatar {
  width: 100px;
  height: 100px;
  display: block;
}

.text {
  font-size: 14px;
}

.item {
  margin-bottom: 18px;
}

.clearfix:before,
.clearfix:after {
  display: table;
  content: '';
}

.clearfix:after {
  clear: both;
}

.box-card {
  margin: auto;
  width: 90%;
}

.elinput {
  width: 60%;
}
</style>
